package socket;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client5 {
    private Socket socket;

    public Client5(){
        try {
            System.out.println("正在启动客户端....");
            socket = new Socket("localhost",8088);
            System.out.println("客户端启动完毕！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        //发送消息给服务端
        try {
            ServerHandler serverHandler = new ServerHandler(socket);
            Thread t = new Thread(serverHandler);
            t.setDaemon(true);
            t.start();

            PrintWriter pw = new PrintWriter(
                    new BufferedWriter(
                            new OutputStreamWriter(
                                    socket.getOutputStream(),"UTF-8"
                            )
                    ),true
            );
            Scanner scan = new Scanner(System.in);
            System.out.println("可以写入:");
            while (true){
                String line = scan.nextLine();
                if ("exit".equals(line)) {
                    break;
                }
                pw.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private class ServerHandler implements Runnable{
        private Socket socket;

        public ServerHandler(Socket socket){
            this.socket = socket;
        }
        @Override
        public void run() {
            try {
                BufferedReader bf = new BufferedReader(
                        new InputStreamReader(
                                socket.getInputStream()
                        )
                );
                String serverMessage;
                while ((serverMessage = bf.readLine()) != null){
                    System.out.println(serverMessage);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Client5 client5 = new Client5();
        client5.start();
    }
}
